using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework;
using Arcadium.Graphics;

namespace Arcadium.Screens.Menus.Sidebar
{
    /// <summary>
    /// Logic implementation of a dropdown list
    /// </summary>
    /// <typeparam name="T"></typeparam>
    class SidebarDropdownList<T> : SidebarComponent
    {
        #region Field

        public List<T> Items { get; set; }
        private int selectedItem = 0, 
            previousSelectedItem = 0;
        public T SelectedItem { get { return Items[selectedItem]; } }

        #endregion

        #region Events

        public event EventHandler<GenericEventArgs<T>> ItemSelected;

        #endregion

        #region Initialization

        public SidebarDropdownList(List<T> items)
        {
            if (items.Count == 0)
                throw new ArgumentException();

            this.Items = items;

            Selected += delegate
            {
                if (LockedFocus)
                {
                    if (selectedItem != previousSelectedItem)
                    {
                        ItemSelected(this, new GenericEventArgs<T>(items[selectedItem]));
                        previousSelectedItem = selectedItem;
                    }
                }
                LockedFocus = !LockedFocus;
            };

            Deselected += delegate
            {
                selectedItem = previousSelectedItem;
                LockedFocus = false;
            };
        }

        #endregion

        #region Input & Draw

        public override void HandleInput(PlayerIndex? ControllingPlayer, InputState input)
        {
            if (input.IsMenuDown(ControllingPlayer) && ++selectedItem == Items.Count)
                    selectedItem = 0;
            if (input.IsMenuUp(ControllingPlayer) && --selectedItem < 0)
                    selectedItem = Items.Count - 1;
        }

        #endregion
    }
}
